In [2]:
with open(fname, "wb") as f:
f.write(data)
with open(fname, "rb") as f:
rows = f.readlines(data)
In [3]:
u"Papa" + u"aè"
Out[3]:
In [13]:
import codecs
with codecs.open('unicode.rst', encoding='utf-8', mode='w+') as f:
f.write(u'\u4500 blah blah blah\n')
f.seek(0)
print repr(f.readline()[:1])
with codecs.open('unicode.rst', encoding='utf-8') as f:
for line in f:
print ("AAA", line)
In [ ]:
The most important tip is:
Software should only work with Unicode strings internally, converting to a particular encoding on output.
In [25]:
class Greeter(object):
def __init__(self, name, s="Ferroni"):
self.name = name
self._surname = s
def hello(self):
print("Hello {0.name}".format(self))
class SayGoodBye(object):
def __init__(self, name, s="Ferroni"):
self.name = name
self._surname = s
def bye(self):
print("Bye {0.name}".format(self))
def hello(self):
print("Baaaaaaye {0.name}".format(self))
class HelloBye(SayGoodBye, Greeter):
def __init__(self, *args, **kwargs):
Greeter.__init__(self, *args, **kwargs)
def hello(self):
return Greeter.hello(self)
hb = HelloBye("Lucaaaa")
hb.bye()
hb.hello()
In [29]:
class Greeter(object):
def __init__(self, name, s="Ferroni"):
self.name = name
self._surname = s
def hello(self):
print("Hello {0.name}".format(self))
class SayGoodByeFabriano(Greeter):
def __init__(self, name="Luca"):
super(SayGoodByeFabriano, self).__init__(name)
self.city = "Fabriano"
def bye(self):
print("Bye from {0.city} {0.name}".format(self))
def hello(self):
super(SayGoodByeFabriano, self).hello()
print("Hello from {0.city} {0.name}".format(self))
hb = SayGoodByeFabriano()
hb.bye()
hb.hello()
In [53]:
import json
import csv
people_fname = r"c:\Users\gigi\lessons-python4beginners\src\gestionale\people_fixture.json"
with open(people_fname, "rb") as fpeople:
PEOPLE = json.load(fpeople)
outfname = r"c:\Users\gigi\a.txt"
class DebugExporter(object):
def do_export(self, f, rows):
for row in rows:
print("{}\n".format(row))
class Exporter(object):
def do_export(self, f, rows):
for row in rows:
f.write("{}\n".format(row))
class JsonExporter(object):
def do_export(self, f, rows):
json.dump(rows, f, indent=2)
class CsvExporter(object):
def do_export(self, f, rows):
fieldnames = rows[0].keys()
writer = csv.DictWriter(
f, fieldnames = fieldnames, delimiter = ";")
writer.writeheader()
for row in rows:
writer.writerow(row)
In [56]:
def apply_exportation(xp, fname, data):
with open(fname, "wb") as f:
xp.do_export(f, rows=data)
In [58]:
xp = JsonExporter()
apply_exportation(xp, outfname, data=PEOPLE)
xpcsv = CsvExporter()
csvfname = outfname.replace(".txt",".csv")
apply_exportation(xpcsv, csvfname, data=PEOPLE)
In [ ]:
# [PEP 249](https://www.python.org/dev/peps/pep-0249/)
# v. gestionale/managers02/db.py
In [ ]:
class SqliteDBManager(object):
def _do_export(self, rows):
cu = self.conn.cursor()
# KO: Never do this -- insecure!
# KO: for row in rows:
# KO: c.execute("INSERT INTO people VALUES ('{name}','{city}','{salary}')".format(**row))
# Do this instead
for row in rows:
t = (row["name"], row["city"], row["salary"])
cu.execute('INSERT INTO people VALUES (?,?,?)', t)
self.conn.commit()
In [32]:
import sqlite3 as db
def create_db(dsn):
conn = db.connect(dsn)
cu = conn.cursor()
cu.execute("CREATE TABLE PEOPLE (name VARCHAR(32), city VARCHAR(32), salary INTEGER)")
conn.close()
def save_db(fname, rows):
conn = db.connect(fname)
conn.row_factory = db.Row # cursore indicizzato anche per chiave
# è possibile definire una propria classe factory
# https://docs.python.org/2.7/library/sqlite3.html?highlight=sqlite3#sqlite3.Connection.row_factory
cu = conn.cursor()
for row in rows:
t = list(row[k] for k in ("name", "city", "salary"))
cu.execute("INSERT INTO PEOPLE VALUES (?,?,?)", t)
conn.commit()
conn.close()
# create_db("mydatabase.db")
help(__builtins__))
In [ ]:
phrase = "happy-python-hacking!"
the_end = u" ".join([s.capitalize() for s in phrase.split("-")])